package com.learning.netease.io.bio;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * ClassName: BioServerHttp
 * Description: 服务端升级，返回HTTP内容
 * Date: 2021/1/10 22:33 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Slf4j
public class BioServerHttp {

    private static ExecutorService threadPool = Executors.newCachedThreadPool();

    public static void main(String[] args) throws Exception {
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            log.info("服务器启动成功");
            while (!serverSocket.isClosed()) {
                Socket request = serverSocket.accept();
                log.info("收到新连接 : " + request.toString());

                threadPool.execute(() -> {
                    try {
                        // 接收数据、打印
                        BufferedReader reader;
                        try (InputStream inputStream = request.getInputStream()) {
                            reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                        }
                        String msg;
                        while ((msg = reader.readLine()) != null) {
                            if (msg.length() == 0) {
                                break;
                            }
                            log.info(msg);
                        }

                        log.info("收到数据,来自：" + request.toString());
                        // 模拟Http协议的响应内容。响应结果 200
                        OutputStream outputStream = request.getOutputStream();
                        outputStream.write("HTTP/1.1 200 OK\r\n".getBytes());
                        outputStream.write("Content-Length: 11\r\n\r\n".getBytes());
                        outputStream.write("Hello World".getBytes());
                        outputStream.flush();
                    } catch (IOException e) {
                        log.error(e.getMessage(), e);
                    }
                });
            }
            serverSocket.close();
        }
    }
}
